package com.jd.jstable.strategy;

import com.jd.jstable.config.KeyMode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 结果可以设置过期时间的策略
 * Created by chenyipu on 2018/4/12.
 */
public abstract class ExpireTimeStrategy extends ResultOrientedStrategy {
    private static final Log logger = LogFactory.getLog(ExpireTimeStrategy.class);

    public abstract void expire(Object invoker, Method method, Object[] args, Object result, Long time, TimeUnit timeUnit, KeyMode keyMode);

    @Override
    public void feed(Object invoker, Method method, Object[] args, Object result, String param, KeyMode keyMode) {
        if(StringUtils.isEmpty(param)){
            expire(invoker, method, args, result, 0L, null, keyMode);
        }
        else {
            String[] params = param.split("-");
            if(params.length!=2){
                logger.error(String.format("ExpireTimeStrategy %s feed param format error, for example:_expire:MILLISECONDS-30000", this.getClass().toString()));
                return;
            }
            TimeUnit timeUnit = null;
            switch(params[0]){
                case "MILLISECONDS":
                    timeUnit = TimeUnit.MILLISECONDS;
                    break;
                case "SECONDS":
                    timeUnit = TimeUnit.SECONDS;
                    break;
                case "MINUTES":
                    timeUnit = TimeUnit.MINUTES;
                    break;
                case "HOURS":
                    timeUnit = TimeUnit.HOURS;
                    break;
                case "DAYS":
                    timeUnit = TimeUnit.DAYS;
                    break;
                default:
                    logger.error(String.format("ExpireTimeStrategy %s feed param format error, for example:_expire:MILLISECONDS-30000", this.getClass().toString()));
                    return;
            }
            expire(invoker, method, args, result, Long.parseLong(params[1]), timeUnit, keyMode);
        }

    }

    private Long convertParamToTime(String param) {
        if(param==null){
            return null;
        }
        return Long.parseLong(param);
    }
}
